package com.open4a.openstudy.manager.api;

import com.open4a.openstudy.common.BaseApi;
import com.open4a.openstudy.common.Parameters;
import com.open4a.openstudy.manager.oauth.OauthManager;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Callback;

/**
 * Created by yangkuo02 on 2017/6/5.
 */

public class ApiManager extends BaseApi {

    private static volatile ApiManager instance;

    public ApiManager() {
    }

    public static ApiManager getInstance() {
        if (instance == null) {
            synchronized (ApiManager.class) {
                if (instance == null) {
                    instance = new ApiManager();
                }
            }
        }
        return instance;
    }

    public void oauth2Token(String code, boolean isRefresh, Callback callback) {
        if (callback == null) {
            return;
        }
        String url = Parameters.OSCHINA_URL + Parameters.PATH_OAUTH2_TOKEN;
        Map<String, String> map = new HashMap<String, String>();
        map.put("client_id", Parameters.APP_ID);
        map.put("client_secret", Parameters.APP_KEY);
        if (isRefresh) {
            map.put("grant_type", "refresh_token");
            map.put("refresh_token", code);
        } else {
            map.put("grant_type", "authorization_code");
            map.put("code", code);
        }
        map.put("redirect_uri", Parameters.REDIRECT_URI);
        map.put("dataType", "json");
        post(url, buildRequestBody(map), callback);
    }

    public void newsList(int catalog, int pageIndex, int pageSize, Callback callback) {
        if (callback == null) {
            return;
        }
        String url = Parameters.OSCHINA_URL + Parameters.PATH_NEWS_LIST;
        Map<String, String> map = new HashMap<String, String>();
        map.put("access_token", OauthManager.getInstance().getAccessToken());
        map.put("catalog", String.valueOf(catalog));
        map.put("pageIndex", String.valueOf(pageIndex));
        map.put("pageSize", String.valueOf(pageSize));
        map.put("dataType", "json");
        post(url, buildRequestBody(map), callback);
    }

    public void newsDetail(long id, Callback callback) {
        if (callback == null) {
            return;
        }
        String url = Parameters.OSCHINA_URL + Parameters.PATH_NEWS_DETAIL;
        Map<String, String> map = new HashMap<String, String>();
        map.put("id", String.valueOf(id));
        map.put("access_token", OauthManager.getInstance().getAccessToken());
        map.put("dataType", "json");
        post(url, buildRequestBody(map), callback);
    }
}
